<template>
  <div class="exchange-records">
    <h2>兑换记录</h2>
    <el-table :data="records" style="width: 100%">
      <el-table-column prop="goodsName" label="商品名称" width="180"></el-table-column>
      <el-table-column prop="coverUrl" label="商品图片" width="120">
        <template #default="{row}">
          <el-image
              style="width: 80px; height: 80px"
              :src="row.coverUrl"
              :preview-src-list="[row.coverUrl]"
              fit="cover"
              v-if="row.coverUrl"
          ></el-image>
          <span v-else>无图片</span>
        </template>
      </el-table-column>
      <el-table-column prop="quantity" label="数量"></el-table-column>
      <el-table-column prop="pointsCost" label="消耗积分"></el-table-column>
      <el-table-column prop="exchangeTime" label="兑换时间" width="180"></el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template #default="{row}">
          <el-tag :type="statusTagMap[row.status]">
            {{ statusMap[row.status] }}
          </el-tag>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import qs from 'qs'

const records = ref([])
const username = localStorage.getItem('username')

const statusMap = {
  0: '待发货',
  1: '已发货',
  2: '已完成',
  3: '已取消'
}

const statusTagMap = {
  0: 'info',
  1: 'primary',
  2: 'success',
  3: 'warning'
}

onMounted(() => {
  getRecords()
})

const getRecords = async () => {
  try {
    const res = await axios.get(BASE_URL+'/api/volunteer/myPointsExchanges', {
      params: { username },
      paramsSerializer: params => qs.stringify(params)
    })
    // 格式化时间
    records.value = res.data.data.map(item => ({
      ...item,
      exchangeTime: formatDateTime(item.exchangeTime)
    }))
  } catch (error) {
    console.error('获取兑换记录失败', error)
  }
}

const formatDateTime = (datetime) => {
  if (!datetime) return ''
  const date = new Date(datetime)
  return date.toLocaleString()
}
</script>

<style scoped>
.exchange-records {
  padding: 20px;
}
</style>